<template>
  <div>
    <div style="padding: 20px">
      <el-card>
        <div class="body">
          <!-- 头部搜索区 -->
          <el-form ref="searchRef" :model="data">
            <el-row type="flex" flex-wrap="wrap">
              <el-col :span="6"
                ><el-form-item prop="tags" label-width="80px" label="标签名称">
                  <el-input
                    v-model="data.tags"
                    size="small"
                    placeholder="请输入"
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="6">
                <el-form-item prop="province" label-width="60px" label="城市">
                  <el-select
                    placeholder="请选择"
                    v-model="data.province"
                    size="small"
                    @change="choseProvince"
                  >
                    <el-option
                      v-for="item in provinces"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="city" label-width="80px" label="地区">
                  <el-select
                    v-model="data.city"
                    placeholder="请选择"
                    size="small"
                    autocomplete="on"
                    @change="choseCity"
                  >
                    <el-option
                      v-for="item in cities"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  prop="shortName"
                  label-width="80px"
                  label="企业简称"
                >
                  <el-input
                    v-model="data.shortName"
                    size="small"
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="6"
                ><el-form-item prop="state" label="状态" label-width="80px">
                  <el-select
                    v-model="data.state"
                    placeholder="请选择"
                    style="width: 212px"
                    size="small"
                  >
                    <el-option
                      v-for="item in states"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select> </el-form-item
              ></el-col>
              <el-col :span="6" style="padding-left: 40px"
                ><el-button @click="resetField" size="small">清除</el-button>
                <el-button
                  type="primary"
                  class="search"
                  @click="search"
                  size="small"
                  >搜索</el-button
                ></el-col
              >
              <el-col :span="12" style="text-align: right"
                ><el-button type="success">
                  <i class="el-icon-edit" @click="add">新增用户</i></el-button
                ></el-col
              >
            </el-row>
          </el-form>
          <!-- 共n条记录 -->
          <elalert :counts="counts"></elalert>
          <!-- 结果区 -->
          <el-table :data="list" style="width: 100%">
            <el-table-column
              align="center"
              prop="id"
              label="序号"
              width="181"
            />
            <el-table-column
              align="center"
              prop="number"
              label="企业编号"
              width="127"
            />
            <el-table-column align="center" prop="shortName" label="企业简称" />
            <el-table-column align="left" prop="tags" label="标签" />
            <el-table-column align="center" prop="creatorID" label="创建者" />
            <el-table-column align="center" prop="addDate" label="创建日期" />
            <el-table-column align="center" prop="remarks" label="备注" />
            <el-table-column align="center" prop="state" label="状态" />
            <el-table-column align="center" label="操作" width="180">
              <template #default="{ row }">
                <el-button type="primary" plain circle @click="edit(row)">
                  <i class="el-icon-edit"></i
                ></el-button>
                <el-button
                  type="warning"
                  v-if="row.state === 1"
                  plain
                  circle
                  @click="forbidden(row)"
                >
                  <i class="el-icon-close"></i
                ></el-button>
                <el-button
                  type="success"
                  v-if="row.state === 2"
                  plain
                  circle
                  @click="forbidden(row)"
                >
                  <i class="el-icon-check"></i
                ></el-button>
                <el-button type="danger" plain circle @click="del(row)">
                  <i class="el-icon-delete"></i
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <elpagination
            :counts="counts"
            :data="data"
            :n="[10, 20, 30, 50]"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          ></elpagination>
        </div>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="showDialog"
      @close="$refs.addRef.resetFields()"
    >
      <el-form ref="addRef" :model="addFormdata" :rules="rules">
        <el-form-item label-width="120px" label="企业名称" prop="shortName"
          ><el-input v-model="addFormdata.shortName"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="所属公司" prop="company"
          ><el-input v-model="addFormdata.company"></el-input>
        </el-form-item>
        <el-form-item label-width="120px">
          <p>https://www.tianyancha.com (在此可查询所属公司全称及简称)</p>
        </el-form-item>

        <el-form-item label-width="120px" label="城市地区" prop="city">
          <el-select
            v-model="addFormdata.province"
            placeholder="请选择"
            @change="choseProvince"
          >
            <el-option
              v-for="item in provinces"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="addFormdata.city"
            placeholder="请选择"
            autocomplete="on"
            @change="choseCity"
          >
            <el-option
              v-for="item in cities"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="120px" label="方向(企业标签)" prop="tags"
          ><el-input v-model="addFormdata.tags"></el-input>
        </el-form-item>

        <el-form-item label-width="120px" label="备注" prop="remarks"
          ><el-input
            v-model="addFormdata.remarks"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elalert from '@/components/elalert/index.vue'
import elpagination from '@/components/elpagination/index.vue'
import { list, add, detail, update, remove } from '@/api/hmmm/companys'
import moment from 'moment'
import ChineseDistricts from '@/utils/area'
export default {
  data() {
    return {
      ChineseDistricts: ChineseDistricts,
      data: {
        page: 1,
        pagesize: 10,
        tags: null,
        province: null,
        city: null,
        shortName: null,
        state: null
      },
      provinces: [],
      cities: [],
      shi1: [],
      states: [
        { id: 1, label: '启用' },
        { id: 2, label: '禁用' }
      ],
      list: [],
      currentPage: 1,
      counts: 1,
      showDialog: false,
      title: '创建用户',
      addFormdata: {
        city: '',
        company: '',
        isFamous: true,
        province: '',
        remarks: '',
        shortName: '',
        tags: ''
      },
      rules: {
        shortName: [
          { required: true, massage: '请输入公司简称', triggers: 'blur' }
        ],
        company: [
          { required: true, massage: '请输入所属公司', triggers: 'blur' }
        ],
        city: [{ required: true, massage: '请输入城市地区', triggers: 'blur' }],
        tags: [{ required: true, massage: '请输入标签', triggers: 'blur' }],
        remarks: [{ required: true, massage: '请输入备注', triggers: 'blur' }]
      },
      comArr: []
    }
  },
  components: { elalert, elpagination },
  created() {
    this.getCompanyList()
    this.getCityData()
  },
  methods: {
    // 获取企业数据
    async getCompanyList() {
      try {
        const { data } = await list(this.data)
        data.items.forEach(item => {
          item.addDate = moment(item.addDate).format('YYYY-MM-DD')
        })
        if (JSON.parse(localStorage.getItem('comArr'))) {
          data.items.forEach(item => {
            JSON.parse(localStorage.getItem('comArr')).forEach(item2 => {
              item.id === item2.id ? (item.state = item2.state) : ''
            })
          })
        }
        this.list = data.items
        this.counts = data.counts
        this.data.page = data.page
        this.data.pagesize = data.pagesize
      } catch (error) {
        console.log(error)
      }
    },
    // 获取全国拿城市
    getCityData() {
      this.ChineseDistricts.forEach(item => {
        // console.log(item)
        item.cityList?.forEach(item2 => {
          this.provinces.push({
            id: item2.code,
            label: item2.name,
            children: item2.areaList
          })
        })
      })
    },
    // 选省
    choseProvince(e) {
      this.cities = []
      this.provinces.forEach(item => {
        if (item.id === e) {
          // console.log(item)
          this.addFormdata.province = item.label
          this.data.province = item.label
          this.shi1 = item.children
          this.data.city = item.children[0].name
          this.addFormdata.city = item.children[0].name
          this.shi1.forEach(citem => {
            this.cities.push({
              id: citem.code,
              label: citem.name
            })
          })
        }
      })
    },
    // 选市
    choseCity(e) {
      this.cities.forEach(item => {
        // console.log(item)
        if (item.id === e) {
          this.addFormdata.city = item.label
          this.data.city = item.label
        }
      })
    },

    handleSizeChange(val) {
      this.data.pagesize = val
      this.getCompanyList()
    },
    handleCurrentChange(val) {
      this.data.page = val
      this.getCompanyList()
    },
    resetField() {
      this.$refs.searchRef.resetFields()
    },
    search() {
      this.getCompanyList()
    },
    async add() {
      this.resetField()
      this.addFormdata.province = ''
      this.data.province = ''
      this.addFormdata.city = ''
      this.title = '创建用户'
      this.showDialog = true
    },
    async save() {
      if (this.title === '创建用户') {
        try {
          await this.$refs.addRef.validate()
          await add(this.addFormdata)
          this.$message.success('创建成功')
          this.data.province = ''
          this.resetField()
          this.getCompanyList()
        } catch (error) {
          console.log(error)
        }
      } else if (this.title === '编辑用户') {
        try {
          await this.$refs.addRef.validate()
          await update(this.addFormdata)
          this.$message.success('编辑成功')
          this.data.province = ''
          this.resetField()
          this.getCompanyList()
        } catch (error) {
          console.log(error)
        }
      }
      this.showDialog = false
    },
    async edit(row) {
      console.log(this.list)
      console.log(row)
      this.title = '编辑用户'
      this.showDialog = true
      const { data } = await detail(row)
      this.provinces.forEach(item => {
        if (item.label === data.province) {
          let e = item.id
          this.choseProvince(e)
        }
      })
      if (data.isFamous === 1) data.isFamous = true
      this.addFormdata = { ...data }
    },
    async del(row) {
      this.$confirm('该项操作不可恢复！确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message.success('删除成功')
          this.getCompanyList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
    },
    forbidden(row) {
      this.$confirm(row.state === 1 ? '确定要禁用吗' : '确定要启用吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          row.state = row.state === 1 ? 2 : 1
          this.$message.success(row.state === 2 ? '禁用成功' : '启用成功')
          this.list.forEach(item => {
            this.comArr.push({ id: item.id, state: item.state })
          })
          localStorage.setItem('comArr', JSON.stringify(this.comArr))
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消成功'
          })
        })
    }
  }
}
</script>

<style scoped lang="scss">
.el-card {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  border-radius: 4px;
  overflow: hidden;
  .body {
    width: 100%;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
      Microsoft YaHei, Arial, sans-serif;
    ::v-deep .el-form {
      .el-row {
        flex-wrap: wrap;
        .el-col {
          .el-form-item {
            margin-bottom: 18px;
            .el-input {
              position: relative;
              display: inline-block;
            }
            .el-button {
              margin-left: 15px;
              padding: 9px 15px;
              border-radius: 3px;
            }
            .search {
              margin-left: 10px;
            }
          }
        }
      }
    }
    ::v-deep .el-table {
      .el-table--fit {
        border-right: 0;
        border-bottom: 0;
      }
    }
    ::v-deep .el-table th.el-table__cell.is-leaf {
      border-bottom: 2px solid #e8e8e8;
      background-color: #fafafa;
    }
    ::v-deep .el-card .body[data-v-eacc1416] .el-table td.el-table__cell div {
      display: flex;
      padding-left: 5px;
      padding-right: 5px;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-break: break-all;
      line-height: 23px;
    }
  }
}
.el-dialog {
  .el-form {
    .el-form-item {
      width: 540px;
      margin-left: 80px;
      .el-select {
        width: 47%;
        margin-right: 10px;
      }
      .el-input {
        width: 100%;
        display: inline-block;
      }
    }
  }
  .dialog-footer {
    text-align: center;
    padding: 10px 20px 20px;
  }
}
</style>
